package edu.tapestry.iddb.client.pages.buddyIM;

import iddb.AbstractResponse;
import iddb.BuddiesInfo;
import iddb.BuddyPOJO;
import iddb.OkResponse;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.ApplicationState;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.BeanModelSource;

import edu.tapestry.iddb.client.helpers.PI;
import edu.tapestry.iddb.client.pages.ErrorPage;
import edu.tapestry.iddb.client.pages.OKPage;
import edu.tapestry.iddb.client.pages.message.SendMessage;
import edu.tapestry.iddb.client.webService.CommandsGenerator;
import edu.tapestry.iddb.client.webService.IDDBProxy;

public class ListBuddyIM {

	@ApplicationState
	private IDDBProxy proxy;
	
	@Persist
	@Property
	private List<BuddyPOJO> buddies;
	
	@Property
	private BuddyPOJO currentBuddy;
	
	@Property
	@Persist
	private PI ident;
	
	@InjectPage
	private SendMessage sendPage;
	
	@InjectPage
	private OKPage ok;

	@InjectPage
	private ErrorPage error;
	
	@Inject
	private BeanModelSource beanModelSource;

	@Inject
	private ComponentResources resources;

	private BeanModel<BuddyPOJO> model;

	public Object initialize(PI ident) {
		
		this.ident = ident;
		
		BuddiesInfo names = (BuddiesInfo) proxy.execute(CommandsGenerator
				.getBuddiesCmd(null, ident.getIdent()));

		this.buddies = new ArrayList<BuddyPOJO>(); 
			
			for(Iterator<String> ii = names.getBuddies().iterator(); ii.hasNext();){
				String name = ii.next();
				
				BuddyPOJO b = new BuddyPOJO();
				b.setUsername(name);
				b.setNick(name);
				buddies.add(b);
			}

		return this;
	}

	void pageLoaded() {
		this.model = beanModelSource.create(BuddyPOJO.class, true, resources
				.getMessages());
		this.model.add("details", null);
	}
	
	public List<BuddyPOJO> getBuddies(){
		return this.buddies;
	}
	
	public Object onActionFromSendLink(String toUsername){
		return sendPage.initialize(ident, toUsername);
	}
	
	public Object onActionFromRemoveLink(String username){
		String groupname = "nazevSkuppiny";
		AbstractResponse resp = proxy.execute(CommandsGenerator.createRemoveBuddy(this.ident.getIdent(), username, groupname));
		
		if (resp instanceof OkResponse){
			return ok;
		}
		else {
			return error.initialize(resp);
		}
	}

}
